import styles from "@styles/chat.module.less";
import Header from "@shared/header";
import Back from "@shared/back";
import GeekIcon from "@shared/geekIcon";
import { io, Socket } from "socket.io-client";
import { useEffect, useRef, useState } from "react";
import { useTypedSelector } from "@store/index";
import { selectToken } from "@slice/credential";

// 声明消息的类型
interface Message {
  type: "robot" | "user";
  message: string;
}

export default function Chat() {
  // 获取用户登录凭据
  const token = useTypedSelector(selectToken);
  // 声明消息数组
  const [messages, setMessage] = useState<Message[]>([]);
  // 记录用户输入的消息
  const [content, setContent] = useState("");
  // 存储 socket 对象
  const socketRef = useRef<Socket | null>(null);

  useEffect(() => {
    // 创建 websocket 连接
    const socket = io("http://toutiao.itheima.net", {
      query: {
        token,
      },
      transports: ["websocket"],
    });
    // 保存 socket 对象
    socketRef.current = socket;
    // 监听连接是否成功
    socket.on("connect", () => {
      // 渲染默认消息
      setMessage([
        { type: "robot", message: "您好，小智同学为您服务。" },
        { type: "robot", message: "请问有什么可以帮您。" },
      ]);
    });
    // 监听连接是否断开
    socket.on("disconnect", () => {
      console.log("websocket 断开连接了");
    });
    // 监听服务端发送的消息
    socket.on("message", (response) => {
      setMessage((messages) => [
        ...messages,
        { type: "robot", message: response.msg },
      ]);
    });
    // 组件卸载之前断开连接
    return () => {
      socket.disconnect();
    };
  }, [token]);

  // 发送消息
  const sendMessage = () => {
    // 将消息保存到本地, 目的是渲染
    setMessage([...messages, { type: "user", message: content }]);
    // 向服务端主动发消息
    socketRef.current?.emit("message", {
      msg: content,
      timestamp: Date.now() + "",
    });
    // 清空用户在文本框中输入的内容
    setContent("");
  };

  return (
    <div className={styles.chat}>
      <Header title={"小智同学"} left={<Back />} />
      <ul className={styles.content}>
        {messages.map((item) => {
          if (item.type === "robot") {
            return (
              <li>
                <div className={styles.avatar}>
                  <GeekIcon type={"iconbtn_xiaozhitongxue"} />
                </div>
                <div className={styles.say}>{item.message}</div>
              </li>
            );
          }
          return (
            <li className={styles.customer}>
              <div className={styles.avatar}>
                <img
                  src={"http://toutiao.itheima.net/images/user_head.jpg"}
                  alt={""}
                />
              </div>
              <div className={styles.say}>你好</div>
            </li>
          );
        })}
      </ul>
      <div className={styles.footer}>
        <div className={styles.edit}>
          <GeekIcon type={"iconbianji"} />
          <input
            value={content}
            onChange={(event) => setContent(event.currentTarget.value)}
            type="text"
            placeholder="请描述你的问题"
          />
        </div>
        <button onClick={sendMessage}>发送</button>
      </div>
    </div>
  );
}
